package top.arryweb.application.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description druid控制台配置
 * @Author mac
 * @Date 2021/5/27
 **/
@Configuration
public class DruidConfig {
  private final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

  /**
   * 将容器中注入一个DruidDataSource的一个数据源并读取前缀为spring.datasource的配置文件的值
   */
  @ConfigurationProperties(prefix = "spring.datasource")
  @Bean
  public DataSource druid() {
    return new DruidDataSource();
  }

  /**
   * 配置一个管理后台的Servlet
   * @return
   */
  @Bean
  public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(
        new StatViewServlet(), "/druid/*");
    Map<String, String> initParams = new HashMap<>();
    //控制台管理用户
    initParams.put("loginUsername", "admin");
    initParams.put("loginPassword", "123456");
    bean.setInitParameters(initParams);
    return bean;
  }

  /**
   * 配置一个监控Filter
   */
  @Bean
  public FilterRegistrationBean webStatFilter(){
    FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
    bean.setFilter(new WebStatFilter());
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    bean.setInitParameters(initParams);
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
  }

  /**
   * druid简单教程  https://blog.csdn.net/yunnysunny/article/details/8657095
   * Druid连接池的使用以及注意事项  https://zhuanlan.zhihu.com/p/130253740
   */
}
